import 'package:flutter/material.dart';
import 'package:overlay_support/overlay_support.dart';

enum ToastPosition { top, bottom }

class _ToastPayload {
  final String message;
  final ToastPosition position;
  final Duration duration;
  final Color backgroundColor;
  final Color textColor;
  final double borderRadius;

  _ToastPayload(
      this.message,
      this.position,
      this.duration,
      this.backgroundColor,
      this.textColor,
      this.borderRadius,
      );
}

// 防抖控制标志
bool _toastLocked = false;

void _showToastOnce(_ToastPayload payload, {Duration lockDuration = const Duration(milliseconds: 3000)}) {
  // 如果处于锁定状态，不弹
  if (_toastLocked) return;

  _toastLocked = true;

  // 弹出 toast
  showOverlayNotification(
        (context) {
      return SafeArea(
        child: Material(
          color: Colors.transparent,
          child: Container(
            margin: payload.position == ToastPosition.top
                ? const EdgeInsets.only(top: 50)
                : const EdgeInsets.only(bottom: 50),
            padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
            decoration: BoxDecoration(
              color: payload.backgroundColor,
              borderRadius: BorderRadius.circular(payload.borderRadius),
              boxShadow: const [
                BoxShadow(
                  color: Colors.black26,
                  blurRadius: 2,
                  offset: Offset(0, 2),
                ),
              ],
            ),
            constraints: const BoxConstraints(maxWidth: 300),
            child: Text(
              payload.message,
              maxLines: 5,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                color: payload.textColor,
                fontSize: 15,
              ),
            ),
          ),
        ),
      );
    },
    duration: payload.duration,
    position: payload.position == ToastPosition.top
        ? NotificationPosition.top
        : NotificationPosition.bottom,
  );

  // 在 lockDuration 后释放锁，允许下一次 toast
  Future.delayed(lockDuration, () {
    _toastLocked = false;
  });
}

void toast(
    String message, {
      ToastPosition position = ToastPosition.top,
      Duration duration = const Duration(seconds: 2),
      Color backgroundColor = Colors.black87,
      Color textColor = Colors.white,
      double borderRadius = 50,
    }) {
  _showToastOnce(
    _ToastPayload(
      message,
      position,
      duration,
      backgroundColor,
      textColor,
      borderRadius,
    ),
  );
}
